import React, { useState, useEffect, useRef } from 'react'
import { Space, Table, message, Tag, Divider } from 'antd';
import {
  CaretDownOutlined
} from '@ant-design/icons';
import { connect } from "react-redux"
import axios from 'axios';

const getRowClassName = (record, index) => {
  let className = '';
  className = index % 2 === 0 ? "oddRow" : "evenRow";
  return className
}

function DevDetail(props) {
  const [messageApi, contextHolder] = message.useMessage();
  const [password, setPassword] = useState(props.row.password)
  const [patch, setPatch] = useState()
  const [app, setApp] = useState()
  const [info, setInfo] = useState()
  const [upgradeBtn, setUpgradeBtn] = useState("升级")
  const clipboardRef = useRef(null);
  const [appupgradeBtn, setAppUpgradeBtn] = useState([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
  useEffect(() => {
    axios.get("/patch/selectall").then(res => {
      setPatch(res.data)
    })
    axios.get("/app/selectAll?deviceId=" + props.row.deviceid).then(res => {
      if (props.row.state === "离线") {
        setAppUpgradeBtn([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
      }
      var data = [...appupgradeBtn]
      for (var i = 0; i < res.data.length; i++) {
        var item = res.data[i]

        if (item.isipgrade === 2 && item.isuse === 1) {
          data[i] = 3
          setAppUpgradeBtn([data])
        }
        const json = JSON.parse(props.row.appupgradeversion);
        for (var j = 0; j < json.length; j++) {
          if (json[j].appName === item.englishname) {
            if (json[j].appVersion !== item.appversion) {
              data[i] = 2
              setAppUpgradeBtn(data)
            }
          }

        }
      }
      setApp(res.data)

    })
    axios.get("alarminfo/selectAll?deviceId=" + props.row.deviceid).then(res => {
      setInfo(res.data)

    })


  }, [])

  const patchUpgrade = (item) => {

    axios.post("/patchupgrade/patchupgrade", {
      deviceid: props.row.deviceid,
      patchname: item.patchname,
      patchversion: item.patchversion,
      isipgrade: 2,
      isuse: 1

    }).then(res => {
      messageApi.open({
        type: 'success',
        content: '正在升级',
        duration: 10,
      });
      setUpgradeBtn("正在升级")
    })

  }

  const resetPassword = () => {
    axios.get("/devicearchives/resetpassword?id=" + props.row.id).then(res => {
      setPassword(res.data)
      messageApi.open({
        type: 'success',
        content: '重置成功',
        duration: 10,
      });
    })

  }
  const appUpgrade = (item, index) => {
    axios.post("/appupgrade/appupgrade", {
      deviceid: props.row.deviceid,
      appname: item.englishname,
      appversion: item.appversion,
      installcontainer: item.installcontainer,
      isipgrade: 2,
      isuse: 1
    }).then(res => {
      messageApi.open({
        type: 'success',
        content: '正在升级',
        duration: 3,
      });
      var data = [...appupgradeBtn]
      data[index] = 3
      setAppUpgradeBtn(data)
    })

  }
  const copyCommand = () => {
    if (navigator.clipboard && window.isSecureContext) {
      // navigator clipboard 向剪贴板写文本
      return navigator.clipboard.writeText(password).then(() => {
        messageApi.open({
          type: 'success',
          content: '复制成功',
          duration: 3,
        });
      });
    } else {
      // 创建text area
      let textArea = document.createElement("textarea");
      textArea.value = password;
      // 使text area不在viewport，同时设置不可见
      textArea.style.position = "absolute";
      textArea.style.opacity = 0;
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      return new Promise((res, rej) => {
        // 执行复制命令并移除文本框
        document.execCommand('copy') ? res() : rej();
        textArea.remove();
        messageApi.open({
          type: 'success',
          content: '复制成功',
          duration: 3,
        });
      });
    }
    // navigator.clipboard.writeText(password).then(() => {
    //   messageApi.open({
    //     type: 'success',
    //     content: '复制成功',
    //     duration: 3,
    //   });
    // })
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      width: "10%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '补丁名称',
      dataIndex: 'patchname',
      key: 'patchname',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '补丁版本',
      dataIndex: 'patchversion',
      key: 'patchversion',
      align: "center",
      render: (text) => {

        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    // {
    //   title: '补丁状态',
    //   dataIndex: 'isIpgrade',
    //   key: 'isIpgrade',
    //   align: "center",
    //   render: (text) => {
    //     if 
    //     return <Tag color="cyan">{text}</Tag>
    //   }
    // },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      align: "center",
      render: (text, item) => {
        if (props.row.state == "离线") {
          return <a style={{ fontSize: "12px", color: "black" }}  >不可升级</a>
        }
        if (props.row.isipgrade === 2 && props.row.isuse === 1) {
          return <a style={{ fontSize: "12px", color: "black" }}  >正在升级</a>
        }

        if (item.patchversion <= props.row.pathupgradeversion) {
          return <a style={{ fontSize: "12px", color: "black" }}  >不可升级</a>
        }
        // if (ver[1].substring(1, 7) + "." + ver[2].substring(1, 5) <= props.row.pathupgradeversion.substring(2, 13)) {
        //   return <a style={{ fontSize: "12px", color: "black" }}  >不可升级</a>
        // }

        return <a style={{ fontSize: "12px", color: upgradeBtn === "升级" ? "" : "black" }} onClick={() => patchUpgrade(item)}>{upgradeBtn}</a>

      }
    },
  ];
  const columnsAPP = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      width: "10%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: 'APP英文名称',
      dataIndex: 'englishname',
      key: 'englishname',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: 'APP中文名称',
      dataIndex: 'chinaname',
      key: 'chinaname',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: 'APP版本',
      dataIndex: 'appversion',
      key: 'appversion',
      align: "center",
      render: (text) => {
        // var ver = props.row.appupgradeversion[index]
        // return <span style={{ fontSize: "12px" }}>{ver.appVersion}</span>
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: 'APP当前版本',
      dataIndex: "nowappversion",
      key: 'nowappversion',
      align: "center",
      render: (text, item, index) => {
        const json = JSON.parse(props.row.appupgradeversion);
        for (var i = 0; i < json.length; i++) {
          if (json[i].appName === item.englishname) {
            var ver = json[i]
            return <span style={{ fontSize: "12px" }}>{ver?.appVersion}</span>
          }
          if (i === json.length - 1) {
            return <span style={{ fontSize: "12px" }}>{item.appversion}</span>
          }

        }
      }
    },
    {
      title: '安装容器',
      dataIndex: 'installcontainer',
      key: 'installcontainer',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      align: "center",
      render: (text, item, index) => {

        return appupgradeBtn[index] === 1 ? <a style={{ fontSize: "12px", color: "black" }}  >不可升级</a> :
          appupgradeBtn[index] === 2 ? <a style={{ fontSize: "12px", }} onClick={() => appUpgrade(item, index)} >升级</a>
            : <a style={{ fontSize: "12px", color: "black" }} onClick={() => appUpgrade(item, index)} >正在升级</a>
      }
    },
  ];
  const columnsInfo = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      width: "10%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '告警信息',
      dataIndex: 'info',
      key: 'info',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '告警时间',
      dataIndex: 'infotime',
      key: 'infotime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    }
  ];
  return (
    <div>
      {contextHolder}
      <Space direction="vertical" size="middle">
        <div>
          设备状态：<Tag color={props.row.state === "在线" ? "cyan" : "red"}>{props.row.state}</Tag>
        </div>
        <div>
          密码：<span>{password}</span><span ref={clipboardRef} style={{ margin: "0 0 0 20px", color: "#1FBBA9", cursor: "pointer" }} onClick={() => copyCommand()}>复制</span><span style={{ margin: "0 0 0 20px", color: "#1FBBA9", cursor: "pointer" }} onClick={() => resetPassword()}>重置</span>
        </div>
        <div>
          系统固件版本：<span>{props.row.pathupgradeversion}</span>
        </div>
      </Space>
      <Divider orientation="left" style={{ fontSize: "14px" }}>系统固件</Divider>
      <Table
        rowClassName={(record, index) => getRowClassName(record, index)}
        rowKey={(item) => item.id}
        columns={columns} dataSource={patch} style={{ border: "1px solid #c9cacac7", margin: "15px 0 0 0", width: "100%" }}
        pagination={false}
        size='small'
      />
      <Divider orientation="left" style={{ fontSize: "14px" }}>APP版本</Divider>
      <Table
        rowClassName={(record, index) => getRowClassName(record, index)}
        rowKey={(item) => item.id}
        columns={columnsAPP} dataSource={app} style={{ border: "1px solid #c9cacac7", margin: "15px 0 0 0", width: "100%", fontSize: "14px" }}
        pagination={false}
        size='small'
      />
      <Divider orientation="left" style={{ fontSize: "14px" }}>告警信息</Divider>
      <Table
        rowClassName={(record, index) => getRowClassName(record, index)}
        rowKey={(item) => item.id}
        columns={columnsInfo} dataSource={info} style={{ border: "1px solid #c9cacac7", margin: "15px 0 0 0", width: "100%", fontSize: "14px" }}
        pagination={false}
        size='small'
      />
    </div>
  )
}
const mapStateToProps = ({ IsDrawerOpen: { openDrawer, row, drawerType } }) => ({
  openDrawer, row, drawerType
})
export default connect(mapStateToProps)(DevDetail);